/*
 * @Author: fanzhaokun@cetc.com.cn
 * @Date: 2019-07-12 11:27:17
 * @Email: fanzhaokun@cetc.com.cn
 * @LastEditors: luoqiang
 * @LastEditTime: 2021-03-11 10:09:39
 */
import Cookies from 'js-cookie';
import { chartOptions } from './chartOptions';

import cloneDeep from 'lodash.clonedeep';

let util = {};

util.title = function (title) {
  title = title || '智慧衢江';
  window.document.title = title;
};

// sort排序，根据属性的大小升序排列
util.compare = function (property) {
  return function (a, b) {
    var value1 = Number(a[property]);
    var value2 = Number(b[property]);
    return value1 - value2;
  };
};
// 深复制数组或者对象
util.cloneDeep = cloneDeep;

/**
 * @description: 组装table数据
 * @param cols {array} 表头数组
 * @param content ｛array｝表内容二维数组
 * @return:
 */
util.concatTableData = function (cols, content) {
  if (cols && cols.length === 0) {
    return [];
  }
  let arr = [];
  content.forEach(item => {
    let obj = {};
    cols.forEach((col, index) => {
      obj[col] = item[index];
    });
    arr.push(obj);
  });

  return arr;
};

util.homeForDiffRole = function (roleName, isAdmin) {
  // 除一般角色外，其他角色具有优先权，如果包含有领导、业务部门、数据管理员、系统管理员等角色，将优先处理这些角色的权限
  let menus = JSON.parse(Cookies.get('menus') || null);
  if (!menus) { return; }
  let homeObj = {
    Warehouse: 'dataCatalog',
    DataGather: 'dataImport',
    DataHandle: 'dataClean',
    DataPush: 'dataPush',
    DataSource: 'dataSource',
    DocProcess: 'document',
    TaskSchedule: 'workflow',
    Statistics: 'query',
    DataService: 'report',
    DataShow: 'total',
    System: 'config',
    SysSetting: 'setting',
  };
  let obj = {
    'leader': 'total',
    'business-department': 'query',
    'data-admin': 'dataCatalog',
    'sys-admin': 'setting',
    'common': homeObj[menus[0]],
  };
  let home = isAdmin === '1' ? 'dataCatalog' : obj[roleName];

  // console.log({ menus, roleName, home });
  return home;
};

util.setCookie = function (name, value) {
  Cookies.set(name, value, { expires: 0.5, sameSite: 'lax', path: process.env.BASE_URL });
};
util.packChartData = function (chartData) {
  let packCharts = [];
  chartData.forEach(element => {
    let { data: chartData, name, options, type, no, col } = element;
    let { fields, values, total } = chartData;
    let dimension =
      options &&
      options.find(item => {
        return item.type === 'dimension';
      }); // 获取维度所在的对象（即x轴相关对象，维度只有一个，直接取对象）
    let quota =
      options &&
      options.filter(item => {
        return item.type === 'quota';
      }); // 获取指标所在数组（指标至少一个，放数组存储）
    let dimensionIndex = dimension && dimension.field; // 取维度在数据中的索引
    if (type === '0') {
      // 表格
      let tableHead = fields;
      let tableData = util.concatTableData(fields, values);
      let charts = {
        type,
        no,
        total,
        title: name,
        tableHead,
        tableData,
        options: options,
        col: col || 2,
      };
      packCharts.push(charts);
    } else if (type === '1') {
      // 列表
      let charts = {
        type,
        no,
        title: name,
        label: fields,
        value: values && values[0],
        options: options && options[0],
        col: col || 2,
      };

      packCharts.push(charts);
    } else if (type === '2' || type === '3') {
      // 折线图或者柱状图
      let chartType = type === '2' ? 'line' : 'bar';

      // 折线图
      let xAxisData = values.map(item => {
        return item[dimensionIndex];
      });
      let quotaIndexes = quota.map(item => {
        return item.field;
      });

      let seriesData = [];

      quotaIndexes.forEach(ele => {
        let arr = values.map(item => {
          return item[ele];
        });

        seriesData.push({
          type: chartType,
          smooth: true,
          data: arr,
          name: fields[ele],
        });
      });

      let lineOptions = cloneDeep(chartOptions.line);
      lineOptions.xAxis.data = xAxisData;

      lineOptions.series = seriesData;
      let charts = {
        type,
        no,
        title: name,
        options: lineOptions,
        col: col || 2,
      };

      packCharts.push(charts);
    } else if (type === '4') {
      // 饼图
      let quotaIndex = quota && quota[0] && quota[0].field; // 扇形图只有一个指标一个维度
      let seriesData = values.map(item => {
        return {
          name: item[dimensionIndex],
          value: item[quotaIndex],
        };
      });

      let pieOptions = cloneDeep(chartOptions.pie);
      pieOptions.series[0].data = seriesData;

      let charts = {
        type,
        no,
        title: name,
        options: pieOptions,
        col: col || 2,
      };
      packCharts.push(charts);
    } else if (type === '5') {
      // 树状图
      let childrenData = values[0] && values[0][1].map(item => {
        return { name: item };
      });
      let seriesData = {
        name: values[0] && values[0][0],
        children: childrenData,
      };
      let treeOptions = cloneDeep(chartOptions.tree);
      treeOptions.series[0].data = [seriesData];
      let charts = {
        type,
        no,
        title: name,
        options: treeOptions,
        col: col || 2,
      };

      packCharts.push(charts);
    } else if (type === '6') {
      // 雷达图
      let quotaIndex = quota && quota[0] && quota[0].field; // 雷达图只有一个指标一个维度
      let radarOptions = cloneDeep(chartOptions.radar);
      let indicator = [];
      let radarData = [];
      values.forEach(item => {
        indicator.push({ text: item[dimensionIndex] });
        radarData.push(item[quotaIndex]);
      });
      radarOptions.radar.indicator = indicator;
      radarOptions.series[0].data = [{ value: radarData }];
      let charts = {
        type,
        no,
        title: name,
        options: radarOptions,
        col: col || 2,
      };
      packCharts.push(charts);
    }
  });
  return packCharts;
};
export function getBrowser () {
  let ua = window.navigator.userAgent;
  let isIE = window['ActiveXObject'] != undefined && ua.indexOf('MSIE') != -1;
  let isFirefox = ua.indexOf('Firefox') != -1;
  let isOpera = window['opr'] != undefined;
  let isChrome = ua.indexOf('Chrome') && window['chrome'];
  let isSafari = ua.indexOf('Safari') != -1 && ua.indexOf('Version') != -1;
  if (isIE) {
    return 'IE';
  } else if (isFirefox) {
    return 'Firefox';
  } else if (isOpera) {
    return 'Opera';
  } else if (isChrome) {
    return 'Chrome';
  } else if (isSafari) {
    return 'Safari';
  } else {
    return 'Unkown';
  }
}
// 回显数据字典
util.selectDictLabel = function (datas, value) {
  var actions = [];
  Object.keys(datas).map((key) => {
    if (datas[key].dictValue == ('' + value)) {
      actions.push(datas[key].dictLabel);
      return false;
    }
  })
  return actions.join('');
}

function formatDate (date, format) {
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return format
}

util.getDateStr = function (AddDayCount, format = 'yyyy-MM-dd') {
  let dd = new Date()
  let time = dd.getTime() + AddDayCount * 24 * 3600 * 1000
  let newDate = new Date(time)
  return formatDate(newDate, format)
}

export default util;
